﻿using Microsoft.AspNetCore.Mvc.Filters;
using SmartCity.Passport.Infrastructure.Interfaces;

namespace SmartCity.Passport.API.Filters
{
    /// <summary>
    /// 全局异常过滤器
    /// </summary>
    public class CustomExeceptionFilters : IExceptionFilter
    {
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<CustomExeceptionFilters> logger;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="logger">日志</param>
        public CustomExeceptionFilters(ILogger<CustomExeceptionFilters> logger)
        {
            this.logger = logger;
        }
        /// <summary>
        /// 全局异常过滤器方法
        /// </summary>
        /// <param name="context">上下文</param>
        public void OnException(ExceptionContext context)
        {
            string actionName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ActionName;
            string controllerName = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).ControllerName;

            //string message=$"控制器【{actionName}】的Action【{controllerName}】发生了异常："+context.Exception.Message;

            //message= $"控制器【{actionName}】的Action【{controllerName}】发生了异常：" + context.Exception.StackTrace;


            string message = $"控制器【{actionName}】的Action【{controllerName}】发生了异常：异常信息为：{context.Exception.Message} 具体位置：{context.Exception.StackTrace}";
            logger.LogError("【全局异常过滤器】"+ message);
        }
    }
}
